﻿using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using System.IO;
using XYAC.Framework.WohuaMesExtend.IHI.Extensions;
using XYAC.Framework.WohuaMesExtend.IHI.Models;

namespace XYAC.Framework.WohuaMesExtend.IHI.DataContext
{
    public class AccessIHIDbContext : DbContext
    {

        public AccessIHIDbContext(IOptionsMonitor<AppConfig> moduleConfig) : base()
        {
            this.ConnectionString = moduleConfig.CurrentValue?.AccessIHIHisConnectionString.Replace("{DateNow}", DateTime.Now.Date.ToString("yyyy-MM-dd"));
            //Database.SetInitializer<AccessIHIBaseContext>(null);
        }
        public DbSet<DwlData> DwlData { get; set; }
        public DbSet<LaserData> LaserData { get; set; }
        public string? ConnectionString { get; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //modelBuilder.HasDefaultSchema("");
            //modelBuilder.Entity<HistoryRow>().ToTable("EFMigrationHistory").HasKey(h => h.MigrationId);
            base.OnModelCreating(modelBuilder);
        }

        /// <summary>
        /// 当DB发生OnConfiguring用于配置数据库
        /// </summary>
        /// <param name="optionsBuilder"></param>
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string modStr = "Persist Security Info=False;Mode=Share Deny None;Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\\HisData\\DB{DateNow}.mdb;";
            var connstr = modStr.Replace("{DateNow}", DateTime.Now.Date.ToString("yyyy-MM-dd"));
            // 配置 SQL Server 数据库连接字符串
            optionsBuilder.UseJet(connstr);
        }

        private bool? _dbFileCreated;
        public bool GetDbFileCreated()
        {
            if (!_dbFileCreated.HasValue)
            {
                string connectionStr = Database.GetConnectionString();

                // 提取 Data Source 的值
                var dataSourceIndex = connectionStr.IndexOf("Data Source=", StringComparison.OrdinalIgnoreCase);
                if (dataSourceIndex < 0)
                {
                    throw new InvalidOperationException("连接字符串中未找到 'Data Source='。");
                }

                // 提取数据库文件路径部分（直到第一个分号或字符串结尾）
                int endIndex = connectionStr.IndexOf(";", dataSourceIndex);
                var dbFilePath = endIndex > dataSourceIndex
                    ? connectionStr.Substring(dataSourceIndex + "Data Source=".Length, endIndex - dataSourceIndex - "Data Source=".Length).Trim()
                    : connectionStr.Substring(dataSourceIndex + "Data Source=".Length).Trim();

                // 获取完整路径并检查文件是否存在
                var fullPath = Path.GetFullPath(dbFilePath);
                var directory = Path.GetDirectoryName(fullPath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }
                _dbFileCreated = File.Exists(fullPath);
            }

            return _dbFileCreated.Value;
        }

    }
}
